import {
    AccessTokenKey,
    BaseApi,
    LocationKey,
    OAuthApi,
    OAuthClientID,
    OAuthClientSecret,
    OpenidKey
} from '../config';
import { SIGNOUT } from '@/vuex/type';

const store = require('../vuex/store');

const getdefaultHeaders = () => {
    let location = wx.getStorageSync(LocationKey);
    if (!location) {
        location = {
            longitude: 0,
            latitude: 0
        };
    }
    return {
        app: 1,
        openid: wx.getStorageSync(OpenidKey),
        longitude: location.longitude || 0,
        latitude: location.latitude || 0,
        Authorization: 'Bearer ' + wx.getStorageSync(AccessTokenKey),
        'X-Requested-With': 'XMLHttpRequest'
    };
};

const defaultOptions = (resolve, reject) => ({
    success: res => {
        if (res.statusCode === 200) {
            if (res.data.errCode) {
                if (res.data.errCode === 401) {
                    wx.removeStorageSync(AccessTokenKey);
                    store.commit(SIGNOUT);
                }
                reject(res.data);
            } else {
                resolve(res.data);
            }
        } else {
            if (res.statusCode === 401) {
                wx.removeStorageSync(AccessTokenKey);
                store.commit(SIGNOUT);
            }
            reject(res.data);
        }
    },
    fail: res => {
        console.log(res);
        if (res.errMsg) {
            reject(res);
        } else {
            reject(res.response.data);
        }
    }
});

const get = (path, data, header = {}) => {
    return new Promise((resolve, reject) => {
        const url = BaseApi + path;
        const option = {
            ...defaultOptions(resolve, reject),
            url,
            data,
            header: {
                ...getdefaultHeaders(),
                ...header
            },
            method: 'GET'
        };
        wx.request(option);
    });
};

const post = (path, data, header = {}) => {
    return new Promise((resolve, reject) => {
        const url = BaseApi + path;
        const option = {
            ...defaultOptions(resolve, reject),
            url,
            data,
            header: {
                ...getdefaultHeaders(),
                ...header
            },
            method: 'POST'
        };
        wx.request(option);
    });
};

/**
 * 上传
 * @param path
 * @param filePath
 * @param options
 * @returns {wx.UploadTask}
 */
const upload = (path, filePath, options = {
    formData: {},
    header: {},
    onProgressUpdate: () => {
    },
    success: () => {
    },
    fail: () => {
    }
}) => {
    const url = BaseApi + path;
    const option = {
        url,
        filePath,
        name: 'file',
        header: {
            ...getdefaultHeaders(),
            ...options.header
        },
        formData: options.formData,
        success: result => {
            if (options.success) {
                options.success(JSON.parse(result.data));
            }
        },
        fail: reason => {
            if (options.fail) {
                options.fail(reason);
            }
        }
    };
    let uploadTask = wx.uploadFile(option);
    uploadTask.onProgressUpdate(result => {
        if (options.onProgressUpdate) {
            options.onProgressUpdate(result);
        }
    });
    return uploadTask;
};

const uploadImage = (filePath, formData = {}, header = {}) => {
    return new Promise(((resolve, reject) => {
        const url = BaseApi + '/material/upload/image';
        const option = {
            ...defaultOptions(resolve, reject),
            url,
            filePath,
            formData,
            name: 'file',
            header: {
                ...getdefaultHeaders(),
                ...header
            },
            method: 'POST'
        };
        wx.uploadFile(option);
    }));
};

/**
 * 上传文件
 * @param filePath
 * @param formData
 * @param header
 * @returns {Promise<unknown>}
 */
const uploadFile = (filePath, formData = {}, header = {}) => {
    return new Promise(((resolve, reject) => {
        const url = BaseApi + '/material/upload/file';
        const option = {
            ...defaultOptions(resolve, reject),
            url,
            filePath,
            formData,
            name: 'file',
            header: {
                ...getdefaultHeaders(),
                ...header
            },
            method: 'POST'
        };
        wx.uploadFile(option);
    }));
};

const login = (username, password, data = {}) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: OAuthApi + '/token',
            method: 'POST',
            data: {
                'grant_type': 'password',
                'client_id': OAuthClientID,
                'client_secret': OAuthClientSecret,
                'username': username,
                'password': password,
                'scope': '*',
                ...data
            },
            success: res => {
                if (res.statusCode === 200) {
                    const { access_token } = res.data;
                    if (access_token) {
                        wx.setStorageSync(AccessTokenKey, access_token);
                        resolve(res.data);
                    } else {
                        reject(res.data);
                    }
                } else {
                    Notify('账号和密码不匹配');
                }
            },
            fail: res => {
                reject(res.response.data);
            }
        });
    });
};

export default {
    get,
    post,
    upload,
    uploadImage,
    uploadFile
};
